<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Install\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\Install\Command\UpgradeCommand;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use Psr\Container\ContainerInterface;

/**
 * 版本升级逻辑 1.4.0（渠道活码原始数据处理）.
 */
class Upgrade1D4D0Logic
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var UpgradeCommand
     */
    private $command;

    /**
     * @var CorpContract
     */
    private $corpService;

    /**
     * @var ChannelCodeContract
     */
    private $channelCodeService;

    /**
     * @var WorkEmployeeContract
     */
    private $workEmployeeService;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function __invoke(UpgradeCommand $command)
    {
        $this->command = $command;
        try {
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->channelCodeService = $this->container->get(ChannelCodeContract::class);
            $this->corpService = $this->container->get(CorpContract::class);
            $this->workEmployeeService = $this->container->get(WorkEmployeeContract::class);

            $this->channelCode();
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('1.4.0升级数据处理失败，错误信息：%s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }

    private function channelCode()
    {
        $this->logger->info('渠道活码数据处理，开始');
        $corps = $this->corpService->getCorps(['id']);
        if (empty($corps)) {
            $this->logger->info('没有需要处理的企业');
            return;
        }
        foreach ($corps as $corp) {
            $this->logger->info(sprintf('处理企业id: %s，开始', (string) $corp['id']));
            $channelCode = $this->channelCodeService->getChannelCodesByCorpId([$corp['id']]);

            if (empty($channelCode)) {
                $this->logger->info('该企业没有渠道活码数据需要处理');
                continue;
            }

            foreach ($channelCode as $item) {
                /* 引流成员设置 */
                $oldDrainageEmployee = Json::decode($item['drainageEmployee']);
                $drainageEmployee = [
                    'type' => 2,
                    'timeSlot' => [],
                    'specialPeriod' => [],
                    'addMax' => [
                        'status' => 0,
                        'employees' => [],
                    ],
                ];
                // addMax
                if (! empty($oldDrainageEmployee['addMax']) && $oldDrainageEmployee['addMax']['status'] === 1) {
                    foreach ($oldDrainageEmployee['addMax']['employees'] as $addMax) {
                        $drainageEmployee['addMax']['employees'][] = ['id' => $addMax['employeeId'], 'name' => $addMax['employeeName'], 'max' => $addMax['max']];
                    }
                }
                // timeSlot
                if (! empty($oldDrainageEmployee['employees'])) {
                    $startTime = '';
                    $endTime = '';
                    $week = [];
                    $employees = [];
                    foreach ($oldDrainageEmployee['employees'] as $oldEmployees) {
                        $week[] = $oldEmployees['week'];
                        foreach ($oldEmployees['timeSlot'] as $timeSlot) {
                            $startTime = $timeSlot['startTime'];
                            $endTime = $timeSlot['endTime'];
                            $slotEmployees = $this->getEmployees($timeSlot['employeeId']);
                            $employees = $slotEmployees;
                        }
                    }
                    $drainageEmployee['timeSlot'][] = ['startTime' => $startTime, 'endTime' => $endTime, 'week' => $week, 'employees' => $employees];
                }
                // specialPeriod
                if (! empty($oldDrainageEmployee['specialPeriod']) && ! empty($oldDrainageEmployee['specialPeriod']['detail']) && $oldDrainageEmployee['specialPeriod']['status'] === 1) {
                    $specialPeriodEmployees = [];
                    foreach ($oldDrainageEmployee['specialPeriod']['detail'] as $detail) {
                        $spEmployees = [];
                        foreach ($detail['timeSlot'] as $detailTimeSlot) {
                            $spEmployees[] = $this->getEmployees($detailTimeSlot['employeeId']);
                        }
                        $specialPeriodEmployees = empty($specialPeriodEmployees) ? $spEmployees : array_merge($specialPeriodEmployees, $spEmployees);
                    }
                    $drainageEmployee['specialPeriod'] = $specialPeriodEmployees;
                }
                /* 欢迎语 */
                $oldWelcomeMessage = Json::decode($item['welcomeMessage']);
                $welcomeMessage = ['words' => '', 'mediumId' => []];
                $spanWelcomeStatus = 0;
                $spanWelcome = [];
                $type = 3;
                if (! empty($oldWelcomeMessage['messageDetail'])) {
                    foreach ($oldWelcomeMessage['messageDetail'] as $oldWelcome) {
                        // 通用欢迎语->消息内容
                        if ((int) $oldWelcome['type'] === 1) {
                            if (! empty($oldWelcome['mediumId'])) {
                                $type = 1;
                                $welcomeMessage['mediumId'] = ['type' => 1, 'id' => $oldWelcome['mediumId']];
                            }
                            if (! empty($oldWelcome['welcomeContent'])) {
                                $type = 1;
                                $welcomeMessage['words'] = $oldWelcome['welcomeContent'];
                            }
                        }
                        // 周期欢迎语->分时段欢迎语
                        if ((int) $oldWelcome['type'] === 2 && $oldWelcome['status'] === 1 && ! empty($oldWelcome['detail'])) {
                            $spanWelcomeStatus = 1;
                            $type = 1;
                            foreach ($oldWelcome['detail'] as $detail) {
                                foreach ($detail['timeSlot'] as $timeSlot) {
                                    $spanWelcome[] = ['week' => [0, 1, 2, 3, 4, 5, 6], 'words' => $timeSlot['welcomeContent'], 'mediumId' => ['type' => 1, 'id' => $timeSlot['mediumId']], 'endTime' => $timeSlot['endTime'], 'startTime' => $timeSlot['startTime']];
                                }
                            }
                        }
                    }
                }
                $data = [
                    'drainage_employee' => Json::encode($drainageEmployee),
                    'welcome_message' => Json::encode($welcomeMessage),
                    'span_welcome_status' => $spanWelcomeStatus,
                    'span_welcome' => Json::encode($spanWelcome),
                    'type' => $type,
                ];
                // 数据修改为新结构
                $this->channelCodeService->updateChannelCodeById($item['id'], $data);
            }

            $this->logger->info(sprintf('处理企业id: %s，结束，成功数量：%d', (string) $corp['id'], (int) count($channelCode)));
        }
        $this->logger->info('渠道活码数据处理，结束');
    }

    private function getEmployees($employeeIds): array
    {
        return $this->workEmployeeService->getWorkEmployeesById($employeeIds, ['id', 'name']);
    }
}
